// 美食街监控页面逻辑：订单队列和取餐队列（按餐厅分组）
(function () {
    var isLoading = false;
    
    // 餐厅配置
    var restaurants = [
        { id: 'sichuan', name: '川菜馆', icon: '🌶️' },
        { id: 'canton', name: '粤菜馆', icon: '🦆' },
        { id: 'japanese', name: '日料店', icon: '🍣' }
    ];
    
    // 更新所有餐厅的订单队列
    function updateAllOrderQueues() {
        if (isLoading) return;
        isLoading = true;
        
        restaurants.forEach(function(restaurant) {
            updateRestaurantOrderQueue(restaurant);
        });
        
        isLoading = false;
    }
    
    // 更新单个餐厅的订单队列
    function updateRestaurantOrderQueue(restaurant) {
        showLoadingState(restaurant.id + 'Order');
        
        // 根据餐厅ID调用对应的API方法
        var apiMethod;
        switch(restaurant.id) {
            case 'sichuan':
                apiMethod = apiService.getSichuanOrderQueue();
                break;
            case 'canton':
                apiMethod = apiService.getCantoneseOrderQueue();
                break;
            case 'japanese':
                apiMethod = apiService.getJapaneseOrderQueue();
                break;
            default:
                throw new Error('未知的餐厅ID: ' + restaurant.id);
        }
        
        apiMethod.then(function (data) {
                console.log(restaurant.name + '订单队列数据:', data);
                
                // 更新订单队列列表
                updateRestaurantOrderQueueList(restaurant, data.orders || []);
                
                hideLoadingState(restaurant.id + 'Order');
            })
            .catch(function (err) {
                console.error('获取' + restaurant.name + '订单队列失败:', err);
                hideLoadingState(restaurant.id + 'Order');
                showRestaurantOrderQueueError(restaurant);
            });
    }
    
    // 更新单个餐厅的订单队列列表
    function updateRestaurantOrderQueueList(restaurant, orders) {
        var orderQueueList = document.getElementById(restaurant.id + 'OrderQueueList');
        var orderCount = document.getElementById(restaurant.id + 'OrderCount');
        
        if (!orderQueueList) return;
        
        // 更新计数器
        if (orderCount) {
            // 计数显示与渲染保持一致：最多显示10条
            orderCount.textContent = Math.min(orders.length, 10);
        }
        
        if (orders.length === 0) {
            orderQueueList.innerHTML = `
                <div class="order-queue-item">
                    <div class="order-info">
                        <span class="order-icon">📋</span>
                        <div class="order-details">
                            <span class="order-number">暂无订单</span>
                            <span class="customer-name">等待新订单</span>
                        </div>
                    </div>
                    <div class="order-status">
                        <span class="order-time">--:--</span>
                        <span class="status-badge empty">空闲</span>
                    </div>
                </div>
            `;
            return;
        }
        
        // 按下单时间倒序排列
        orders.sort(function(a, b) {
            return new Date(b.orderTime) - new Date(a.orderTime);
        });
        
        // 仅显示前10条
        var displayOrders = orders.slice(0, 10);

        var html = '';
        displayOrders.forEach(function(order) {
            var orderTime = new Date(order.orderTime);
            var timeStr = orderTime.getHours().toString().padStart(2, '0') + ':' + 
                         orderTime.getMinutes().toString().padStart(2, '0');
            
            var statusClass = getOrderStatusClass(order.status);
            var statusText = getOrderStatusText(order.status);
            
            html += `
                <div class="order-queue-item">
                    <div class="order-info">
                        <span class="order-icon">📋</span>
                        <div class="order-details">
                            <span class="order-number">${order.orderNumber}</span>
                            <span class="customer-name">${order.customerName}</span>
                        </div>
                    </div>
                    <div class="order-status">
                        <span class="order-time">${timeStr}</span>
                        <span class="status-badge ${statusClass}">${statusText}</span>
                    </div>
                </div>
            `;
        });
        
        orderQueueList.innerHTML = html;
    }
    
    // 更新所有餐厅的取餐队列
    function updateAllPickupQueues() {
        restaurants.forEach(function(restaurant) {
            updateRestaurantPickupQueue(restaurant);
        });
    }
    
    // 更新单个餐厅的取餐队列
    function updateRestaurantPickupQueue(restaurant) {
        // 根据餐厅ID调用对应的取餐队列API方法
        var apiMethod;
        switch(restaurant.id) {
            case 'sichuan':
                apiMethod = apiService.getSichuanPickupQueue();
                break;
            case 'canton':
                apiMethod = apiService.getCantonesePickupQueue();
                break;
            case 'japanese':
                apiMethod = apiService.getJapanesePickupQueue();
                break;
            default:
                throw new Error('未知的餐厅ID: ' + restaurant.id);
        }
        
        apiMethod.then(function (data) {
                console.log(restaurant.name + '取餐队列数据:', data);
                
                // 更新取餐队列列表
                updateRestaurantPickupQueueList(restaurant, data.pickups || []);
            })
            .catch(function (err) {
                console.error('获取' + restaurant.name + '取餐队列失败:', err);
                showRestaurantPickupQueueError(restaurant);
            });
    }
    
    // 更新单个餐厅的取餐队列列表
    function updateRestaurantPickupQueueList(restaurant, pickups) {
        var pickupQueueGrid = document.getElementById(restaurant.id + 'PickupQueueGrid');
        var pickupCount = document.getElementById(restaurant.id + 'PickupCount');
        
        if (!pickupQueueGrid) return;
        
        // 更新计数器
        if (pickupCount) {
            pickupCount.textContent = pickups.length;
        }
        
        // 按下单时间正序排列（最早的在前）
        pickups.sort(function(a, b) {
            return new Date(a.orderTime) - new Date(b.orderTime);
        });
        
        // 按实际数据渲染所有取餐项（取消固定5个限制，不再补空位）
        var html = '';
        pickups.forEach(function(pickup) {
            var orderTime = new Date(pickup.orderTime);
            var timeStr = orderTime.getHours().toString().padStart(2, '0') + ':' + 
                         orderTime.getMinutes().toString().padStart(2, '0');
            
            html += `
                <div class="pickup-slot occupied">
                    <div class="pickup-info">
                        <span class="pickup-icon">🍽️</span>
                        <div class="pickup-details">
                            <span class="pickup-number">${pickup.orderNumber}</span>
                            <span class="customer-name">${pickup.customerName}</span>
                        </div>
                    </div>
                    <div class="pickup-time">${timeStr}</div>
                </div>
            `;
        });
        
        pickupQueueGrid.innerHTML = html;
    }
    
    
    // 显示餐厅订单队列错误
    function showRestaurantOrderQueueError(restaurant) {
        var orderQueueList = document.getElementById(restaurant.id + 'OrderQueueList');
        if (!orderQueueList) return;
        
        orderQueueList.innerHTML = `
            <div class="order-queue-item error">
                <div class="order-info">
                    <span class="order-icon">❌</span>
                    <div class="order-details">
                        <span class="order-number">连接失败</span>
                        <span class="customer-name">无法获取${restaurant.name}订单数据</span>
                    </div>
                </div>
                <div class="order-status">
                    <span class="order-time">--:--</span>
                    <span class="status-badge error">错误</span>
                </div>
            </div>
        `;
    }
    
    // 显示餐厅取餐队列错误
    function showRestaurantPickupQueueError(restaurant) {
        var pickupQueueGrid = document.getElementById(restaurant.id + 'PickupQueueGrid');
        if (!pickupQueueGrid) return;
        
        pickupQueueGrid.innerHTML = `
            <div class="pickup-slot error">
                <div class="pickup-info">
                    <span class="pickup-icon">❌</span>
                    <div class="pickup-details">
                        <span class="pickup-number">连接失败</span>
                        <span class="customer-name">无法获取${restaurant.name}取餐数据</span>
                    </div>
                </div>
                <div class="pickup-time">--:--</div>
            </div>
        `;
    }
    
    // 显示加载状态
    function showLoadingState(type) {
        if (type.includes('Order')) {
            var restaurantId = type.replace('Order', '');
            var orderQueueList = document.getElementById(restaurantId + 'OrderQueueList');
            if (orderQueueList) {
                orderQueueList.classList.add('loading');
            }
        } else if (type.includes('Pickup')) {
            var restaurantId = type.replace('Pickup', '');
            var pickupQueueList = document.getElementById(restaurantId + 'PickupQueueList');
            if (pickupQueueList) {
                pickupQueueList.classList.add('loading');
            }
        }
    }
    
    // 隐藏加载状态
    function hideLoadingState(type) {
        if (type.includes('Order')) {
            var restaurantId = type.replace('Order', '');
            var orderQueueList = document.getElementById(restaurantId + 'OrderQueueList');
            if (orderQueueList) {
                orderQueueList.classList.remove('loading');
            }
        } else if (type.includes('Pickup')) {
            var restaurantId = type.replace('Pickup', '');
            var pickupQueueList = document.getElementById(restaurantId + 'PickupQueueList');
            if (pickupQueueList) {
                pickupQueueList.classList.remove('loading');
            }
        }
    }
    
    // 获取订单状态样式类
    function getOrderStatusClass(status) {
        var statusMap = {
            'pending': 'pending',
            'processing': 'processing',
            'ready': 'ready',
            'completed': 'completed',
            'cancelled': 'cancelled'
        };
        return statusMap[status] || 'pending';
    }
    
    // 获取订单状态文本
    function getOrderStatusText(status) {
        var statusMap = {
            'pending': '待处理',
            'processing': '处理中',
            'ready': '已就绪',
            'completed': '已完成',
            'cancelled': '已取消'
        };
        return statusMap[status] || '待处理';
    }
    
    // 初始化页面
    function init() {
        console.log('美食街监控页面初始化');
        
        // 立即更新一次数据
        updateAllOrderQueues();
        updateAllPickupQueues();
        
        // 设置定时更新（每30秒）
        setInterval(function() {
            updateAllOrderQueues();
            updateAllPickupQueues();
        }, 30000);
    }
    
    // 页面加载完成后初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();